//
//  FamilyAddressAddController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/3/12.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

class FamilyAddressAddController: BaseViewController {
    
    private var viewModel = FamilyAddViewModel(model: FamilyAddModel()) {
        didSet {
            tableView.reloadData()
        }
    }
    
    var updateClosure: (() -> Void)?
    
    var cells: [IndexPath: FamilyAddressAddCell] = [:]
    
    private let addressId: String
    
    init(addressId: String = "") {
        self.addressId = addressId
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "添加地址"
        
        if !addressId.isEmpty { loadData() }
    }

    @IBOutlet private weak var activityView: UIActivityIndicatorView!
    
    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.register(FamilyAddressAddCell.nibForCell(),
                               forCellReuseIdentifier: FamilyAddressAddCell.reuseIdentifier())
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
            tap.cancelsTouchesInView = false
            tableView.addGestureRecognizer(tap)
        }
    }
}

extension FamilyAddressAddController {
    private func loadData() {
        activityView.startAnimating()
        FamilyAddViewModel.getReceiveAddressDetail(addressId: addressId, success: { model in
            self.activityView.stopAnimating()
            self.viewModel = FamilyAddViewModel(model: model)
        }) { errorMsg in
            self.activityView.stopAnimating()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    @objc private func dismissKeyboard() {
        tableView.endEditing(true)
    }
}

extension FamilyAddressAddController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfAddressRows
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell: FamilyAddressAddCell?
        if let o = cells[indexPath] {
            cell = o
        } else {
            cell = tableView.dequeueReusableCell(withIdentifier: FamilyAddressAddCell.reuseIdentifier(), for: indexPath) as? FamilyAddressAddCell
            cells[indexPath] = cell
        }
        guard let cell = cell else {
            return UITableViewCell()
        }
        cell.delegate = self
        let cellType = FamilyAddressAddCellType(rawValue: indexPath.row) ?? .name
        cell.configure(with: viewModel, cellType: cellType)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellType = FamilyAddressAddCellType(rawValue: indexPath.row) ?? .name
        switch cellType {
        case .sure: return 110
        default: return 60
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let cellType = FamilyAddressAddCellType(rawValue: indexPath.row) ?? .name
        
        if cellType == .area {
            let addressVc = AddressViewController()
            addressVc.modalPresentationStyle = .custom
            addressVc.chooseClosure = { [weak self] model in
                guard let self = self else { return }
                self.viewModel.area = "\(model.provinceName) \(model.cityName) \(model.areaName)"
                self.viewModel.provinceId = model.provinceId
                self.viewModel.cityId = model.cityId
                self.viewModel.regionId = model.areaId
                self.tableView.reloadData()
            }
            present(addressVc, animated: true) {
                addressVc.view.backgroundColor = UIColor.black.withAlphaComponent(0.36)
            }
        }
    }
}

extension FamilyAddressAddController: FamilyAddressAddCellDelegate {
    func addressAddCell(_ cell: FamilyAddressAddCell, didEndEditing vm: FamilyAddViewModel) {
        viewModel = vm
    }
    
    func addressAddCell(_ cell: FamilyAddressAddCell, didClickedCommonly vm: FamilyAddViewModel) {
        viewModel = vm
    }
    
    func addressAddCell(didClickedSure cell: FamilyAddressAddCell) {
        if !viewModel.isReceiveName {
            HUDTool.show(message: viewModel.nameMsg)
            return
        }
        
        if !viewModel.isReceivePhone {
            HUDTool.show(message: viewModel.phoneMsg)
            return
        }
        
        if !viewModel.isArea {
            HUDTool.show(message: viewModel.areaMsg)
            return
        }
        
        let paras: [String: Any] = [
            "id": viewModel.id,
            "consigneeName": viewModel.receiveName,
            "consigneePhone": viewModel.receivePhone,
            "province": viewModel.provinceId,
            "city": viewModel.cityId,
            "region": viewModel.regionId,
            "addr": viewModel.addr,
            "isDefault": viewModel.isDefault,
        ]
        
        FamilyAddViewModel.addAndEditReceiveAddress(paras: paras) { (errorMsg, code) in
            switch code {
            case .success:
                HUDTool.show(message: "添加成功")
                self.updateClosure?()
                self.navigationController?.popViewController(animated: true)
            case .failure:
                HUDTool.showError(message: errorMsg)
            }
        }
    }
}

